package user

import (
	"errors"
	"github.com/jinzhu/gorm"
	"server/base"
	user3 "server/common/models/user"
	"server/pkg/utils"
	"time"
)

var AuthService = new(authService)

type authService struct{}

func (s *authService) Login(openId string) (user3.UserAuth, string, error) {
	var (
		user     user3.User
		userAuth user3.UserAuth
		err      error
		token    string
	)

	err = base.App.Mysql.Object.Find(&userAuth, "open_id = ?", openId).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return userAuth, token, err
	}
	if userAuth.Id == 0 {
		userAuth, err = s.createUser(openId)
		if err != nil {
			return userAuth, token, err
		}
	}

	token = utils.EncodeToken(userAuth.Id, "user")

	base.App.Mysql.Object.Find(&user, "user_id = ?", userAuth.Id)
	return userAuth, token, nil
}

func (s *authService) createUser(openId string) (user3.UserAuth, error) {
	now := time.Now().Unix()

	var userAuth user3.UserAuth

	err := base.App.Mysql.Object.Transaction(func(tx *gorm.DB) error {
		var err error
		// 新建用户授权表
		userAuth = user3.UserAuth{Status: "wait", OpenId: openId, CreateTime: now, UpdateTime: now}
		err = tx.Create(&userAuth).Error
		if err != nil {
			return err
		}

		// 新建用户
		user := user3.User{UserId: userAuth.Id, CreateTime: now, UpdateTime: now, Type: "user"}
		err = tx.Create(&user).Error
		if err != nil {
			return err
		}

		// 新建用户资料
		userIntro := user3.UserIntro{UserId: user.UserId, CreateTime: now, UpdateTime: now}
		err = tx.Create(&userIntro).Error
		if err != nil {
			return err
		}

		// 新建用户匹配条件
		userMatchWhere := user3.UserMatchWhere{UserId: user.UserId, CreateTime: now, UpdateTime: now}
		err = tx.Create(&userMatchWhere).Error
		return err
	})

	if err != nil {
		return userAuth, errors.New("创建用户失败")
	}

	return userAuth, nil
}
